<?php
namespace jy_feewu;
defined('BY_JYA') or exit('error');
/*
	分销佣金
	
*/
class commission extends \plugin{
	/*
		生成佣金
	*/
	function create($order){
		$level=intval($this->setting['level']);
		$level=$level?:3;
		$this->order=$order;
		$member=pdo_get('jy_commission_member',array('mid'=>$order['mid']),array('sale_mid','mid','is_agent','agent_id'));
		//分销保护期
		if($member['agent_id']){
			$isbao_time=model('jy_commission/member')->upbao_time($order['mid']);
		}
		if($member['is_agent']){
			$agent_id=$member['mid'];
			$this->get_yuefee($member);
		}else{
			$agent_id=$member['agent_id'];
		}
		//自购升级
		if($member['is_agent']){
				pdo_update('jy_commission_member',array('myorder_price +='=>$order['price']),array('mid'=>$order['mid']));
				model('jy_commission/member')->update_agent_level($order['mid'],$order['id']);
		}
		$this->commission_order=array(
			'uniacid'=>$_SESSION['uniacid'],
			'mid'=>$this->order['mid'],
			'ordersn'=>$this->order['ordersn'],
			'order_price'=>$this->order['price'],
			'plugin_name'=>'jy_feewu',
			'commission_money'=>0,
			'area_money'=>0,
			'xuni_money'=>0,
			'jifen'=>0,
			'createtime'=>TIMESTAMP,
		);
		//佣金计算方式，是否扣除运费
		if($this->setting['commissiontype']==1){
			$this->commission_order['commission_price']=$this->order['price'];
		}else{
			$this->commission_order['commission_price']=$this->order['price']-$this->order['dispatchprice'];
		}
		//当分销层级大于0时，逐次寻找上级推荐人并计算佣金
		$sale_mid=$member['sale_mid'];
		for($i=0;$i<$level;$i++){
			//直销奖励
			if($sale_mid){
				$this->create_commission($sale_mid,$i+1,true);
			}
			if(!$agent_id){
				//如果没有上级，但是层级继续。所有奖励都给自己（要是代理商）。
				if($member['is_agent'] && !$member['stop']){
					$this->create_commission($member['mid'],$i+1);
				}
			}else{
				$agent_id=$this->create_commission($agent_id,$i+1);
			}
		}
		//生成分销订单
		pdo_insert('jy_commission_order',$this->commission_order);
		if($order['sendtype']==3){
			$status=pdo_getcolumn('jy_weishop_order',array('id'=>$order['id'],'uniacid'=>$_SESSION['uniacid']),'status');
			if($status==3){
				model('jy_commission/commission')->order_complete($order);
			}
		}
		return true;
	}
	function getfee($member,$commission_level=1){
		if(!$member['level_id']){
				//获取默认等级佣金比例
				$level_commissions=plugin('jy_commission')->plugin_setting('default_level');
				$level_id=0;
				$commission_per=$level_commissions['commission'.$commission_level];
		}else{
				$level=pdo_get('jy_commission_level',array('id'=>$member['level_id'],'uniacid'=>$_SESSION['uniacid']));
				$level_commissions=json_decode($level['commissions'],true);
				$level_id=$level['id'];
				$commission_per=$level_commissions['commission'.$commission_level];
		}
		$money=0;
		$order_price=$this->commission_order['commission_price'];
		//先检查是否存在商品独立佣金规则，如果存在则对订单相应商品部分金额单独计算佣金
		//非按笔计算
		if($this->setting['get_buyordernum']!=1){
				foreach($this->order['goods'] as $goods){
					$total_price=$goods['total_price']?$goods['total_price']:pdo_getcolumn('jy_weishop_order_goods',array('id'=>$goods['id']),'total_price');
					$goods_commission=pdo_get('jy_commission_goods',array('goods_id'=>$goods['goodsid']));
					if($goods_commission['ignore'] || !$goods_commission['id']){
						if($goods_commission['ignore']){
							$order_price=$order_price-$total_price;
						}
						//只要有一个商品，没有独立设置分销，就订单计算佣金
						$this->needorder=true;
						continue;
					}
					//如果商品单独设置佣金，将减少本商品的金额
					$order_price=$order_price-$total_price;
					$goods_commission['commissions']=$goods_commission['commissions']?json_decode($goods_commission['commissions'],true):array();
					foreach($goods_commission['commissions'] as $gc){
						if($gc['level_id']==0){
							$demogoods_commission_per=$gc['commission'.$commission_level];
						}
						if($gc['level_id']!=$level_id){
							continue;
						}else{
							$goods_commission_per=$gc['commission'.$commission_level];
							break;
						}
					}
					$goods_commission_per=$goods_commission_per?:$demogoods_commission_per;
					$goods_commission_per=$goods_commission_per?:$commission_per;	
					if(substr($goods_commission_per,-1)=='%'){
						$goods_commission_money=($total_price*substr($goods_commission_per,0,-1))/100;
						$money+=$goods_commission_money;
					}else{
						$goods_commission_money=$goods_commission_per*$goods['total'];
						$money+=$goods_commission_money;
					}
				}
		}
		if($this->needorder){
				if($order_price>0 && $this->setting['get_buyordernum']!=1){
					$order_commission_money=intval($order_price*$commission_per)/100;
					$money+=$order_commission_money;
					$remark['order_commission']=array('order_price'=>$order_price,'commission_per'=>$commission_per,'commission_money'=>$order_commission_money);
				}elseif($order_price>0 && $this->setting['get_buyordernum']==1){//按笔分销
					$order_commission_money=$commission_per;
					$money+=$order_commission_money;
				}
		}
		return $money;
	}
	function create_commission($agent_id,$commission_level=0,$is_sale){
		$member=pdo_get('jy_commission_member',array('mid'=>$agent_id));
		if(!$member['is_agent'] || $member['stop']){
			return false;
		}		
		$money=$this->getfee($member,$commission_level);
		$remark=array(
				'commission_level'=>$commission_level,
				'order_price'=>$this->commission_order['commission_price'],
				'goods_commission'=>array(),
				'commission_money'=>$money,
		);
		if($money>0){
				$jifen=0;
				if($this->setting['jifenrate']){					
					$jifen=$this->setting['jifenrate']*$money/100;
					$money=$money-$jifen;
					$jifenrateup=$this->setting['jifenrateup']?:1;
					$jifen=intval($jifen*$jifenrateup);
				}
				$this->commission_order['jifen']+=$jifen;
				$this->commission_order['commission_money']+=$money;
				$new_commission=array(
					'uniacid'=>$_SESSION['uniacid'],
					'mid'=>$member['mid'],
					'level'=>$commission_level,
					'ordersn'=>$this->order['ordersn'],
					'money'=>$money,
					'jifen'=>$jifen?:0,
					'remark'=>ijson_encode($remark),
					'createtime'=>TIMESTAMP,
					'is_sale'=>$is_sale?1:0,
					'status'=>0,
				);
				pdo_insert('jy_commission_commission',$new_commission);
				model('jy_weishop/notice')->notice_fenxiao_feeadd($agent_id,$new_commission['money']);
		}
		//此处判断分销商是否满足升级条件，如果满足则升级分销商等级
		$member_update=array(
				'order_price'=>$member['order_price']+$this->commission_order['order_price'],
				'order_num'=>$member['order_num']+1,
		);
		if($commission_level==1){
				$member_update['order_price_next']=$member['order_price_next']+$this->commission_order['order_price'];
				$member_update['order_num_next']=$member['order_num_next']+1;
		}
		pdo_update('jy_commission_member',$member_update,array('mid'=>$member['mid']));
		model('jy_commission/member')->update_agent_level($member['mid']);
		//如果他的上级是我
		$ta_agent_id=pdo_getcolumn('jy_commission_member',array('mid'=>$member['agent_id']),'agent_id');
		if($ta_agent_id==$agent_id){
			return false;
		}
		return $member['agent_id'];
	}
	//月度奖励
	function get_yuefee($member){
		$basic=$this->plugin_setting('basic');
		if(!$basic['is_yuefee'] || !$basic['man_yuefee'] || !$basic['get_yuefee']){
			return false;	
		}
		$isget=pdo_count('jy_commission_commission',array('mid'=>$member['mid'],'level'=>21),'mid');
		if($isget){
			return false;
		}
		$agent_ids=pdo_getall('jy_commission_member',array('agent_id'=>$member['mid']),array('mid'),'mid');
		if($agent_ids){
			$agent_ids=array_keys($agent_ids);
		}
		$agent_ids[]=$member['mid'];
		$allfee=pdo_getsum('jy_weishop_order',array('ispay'=>1,'uniacid'=>$_SESSION['uniacid'],'mid'=>$agent_ids),'price');
		if($allfee>0){
			if($basic['is_yuefee'] && $basic['man_yuefee'] && $basic['get_yuefee']){
				$new_commission=array(
					'uniacid'=>$_SESSION['uniacid'],
					'mid'=>$member['mid'],
					'level'=>21,
					'money'=>$basic['get_yuefee'],
					'createtime'=>TIMESTAMP,
					'status'=>0,
				);
				pdo_insert('jy_commission_commission',$new_commission);
			}
		}
		return true;
	}
	public function commission_remark($remark){
		if(!$remark){
			return '';
		}
		$remark=json_decode($remark,true);
		$goods_str='';
		if($remark['goods_commission']){
			foreach($remark['goods_commission'] as $goods){
				$goods['title']=pdo_getcolumn('jy_weishop_goods',array('id'=>$goods['goods_id']),'title');
				$goods_str.="商品ID【{$goods['goods_id']}】，商品名称【{$goods['title']}】，商品数量【{$goods['total']}】，商品总价【{$goods['total_price']}】，佣金规则【{$goods['commission_per']}】，分销佣金【{$goods['commission_money']}】\n";
			}
		}else{
			$goods_str='未启用';
		}
		$remark['level_title']=pdo_getcolumn('jy_commission_level',array('uniacid'=>$_SESSION['uniacid'],'level'=>$remark['commission_level']),'title');
		$remark['level_title']=$remark['level_title']?:'默认等级';
		$remark_str=<<<TPL
分销商等级ID【{$remark['level_id']}】，等级名称【{$remark['level_title']}】，佣金等级【{$remark['commission_level']}】，订单总价【{$remark['order_price']}】
商品独立佣金：
{$goods_str}
订单佣金：
除去设置独立佣金的商品外订单金额【{$remark['order_commission']['order_price']}】，佣金规则【{$remark['order_commission']['commission_per']}%】，分销佣金【{$remark['order_commission']['commission_money']}】
佣金总计：【{$remark['commission_money']}】
TPL;
		return $remark_str;
	}
}